<template>
    <div ref="containerRef" class="mx-16">
        <div class="px-2 mx-auto max-w-[1600px] mt-4">
            <el-page-header :icon="ArrowLeft" @back="router.back()">
                <template #content>
                    <div class="p-2 flex items-end">
                        <div class="text-2xl mr-4">{{ title }}</div>
                        <div class="text-gray-400 text-sm">
                            {{ caseData.viewCount }} 次浏览
                        </div>
                    </div>
                </template>
                <template #extra>
                    <el-button
                        class="ml-auto"
                        :icon="Share"
                        @click="handleShare"
                    >
                        分享
                    </el-button>
                </template>
            </el-page-header>
        </div>
        <div class="mx-auto max-w-[1600px]">
            <div class="p-2 my-2">
                <component
                    :is="imported?.before.component"
                    :props="imported?.before.props"
                />
            </div>
            <div class="flex">
                <div
                    id="leafer-view"
                    class="flex-1 flex-shrink-0 h-[800px] mr-2 border border-slate-100 rounded"
                ></div>
                <div class="flex-shrink-0 w-[400px] h-[800px]">
                    <Chat
                        ref="chatRef"
                        @choice="handleChoice"
                        :get-context-description="
                            imported?.getContextDescription || (() => [])
                        "
                        :knowledge-base="caseData.knowledgeBase"
                    />
                </div>
            </div>
            <div class="p-2 my-4">
                <component
                    :is="imported?.after.component"
                    :props="imported?.after.props"
                />
            </div>
            <div class="p-2 my-4" style="width: calc(100% - 400px)">
                <MDRender :value="caseData.doc" />
            </div>
            <div
                class="my-12"
                style="width: calc(100% - 400px)"
                v-if="route.query.id"
            >
                <div class="text-2xl font-bold mb-4">评论</div>
                <SendComment type="tcase" :item-id="+route.query.id" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts" name="Case">
import { getListUnauth } from '@/apis/unauthCrud'
import Chat from '@/components/Chat/Chat.vue'
import MDRender from '@/components/MDRender.vue'
import SendComment from '@/components/SendComment.vue'
import { ITCaseExportType } from '@/teaching-cases/interfaces'
import { ArrowLeft, Share } from '@element-plus/icons-vue'
import '@leafer-in/animate'
import '@leafer-in/color'
import '@leafer-in/editor'
import '@leafer-in/flow'
import '@leafer-in/resize'
import '@leafer-in/view' // 视口控制插件
import '@leafer-in/viewport' // 导入视口插件
import '@leafer-ui/core'
import { App } from '@leafer-ui/core'
import '@leafer-ui/draw'
import { ElMessage } from 'element-plus'
import 'leafer-editor'
import throttle from 'lodash/throttle'
import { onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ICaseListItem } from './CaseList/caseList'

const route = useRoute()
const router = useRouter()

const containerRef = ref<HTMLDivElement | null>(null)
const chatRef = ref<any>(null)

let leaferApp: App | null = null
const title = ref('正在加载...')
const caseData = ref<ICaseListItem>({
    title: '',
    key: '',
})

let imported = shallowRef<ITCaseExportType | null>(null)

let modules = import.meta.glob('@/teaching-cases/*/index.ts')

// 案例事件
const handleCaseEvent = (eventName: string, ..._args: any[]) => {
    const questions = caseData.value.questions
    if (!questions || !questions.length) return
    const index = questions.findIndex((v) => {
        return v.trigger === eventName
    })
    if (index === -1 || !chatRef.value || questions[index].asked) return
    questions[index].asked = true
    // console.log(chatRef.value.insertMessage)
    // console.log(caseData.value)
    chatRef.value.insertMessage && chatRef.value.insertMessage(questions[index])
}

// ai聊天单选题选择答案
const handleChoice = (id: string | number, answer: string) => {
    console.log('CASE:', id, answer, 'AI选择答案')
}

// 加载案例
const load = async (url: string) => {
    if (!leaferApp) {
        return
    }

    const moduleImport = modules[url]

    if (!moduleImport) {
        console.error('找不到模块', url)
        return
    }

    const tCase: ITCaseExportType = ((await moduleImport()) as any).default

    if (tCase.emitter) {
        tCase.emitter.onAll(handleCaseEvent)
    }

    leaferApp.tree.clear()
    leaferApp.tree.add(tCase.ui)

    title.value = tCase.title

    imported.value = tCase
}

// 获取当前案例的详细信息
const getData = async () => {
    const id = route.query.id
    if (!id) return
    const res = await getListUnauth(
        'teachCases',
        {
            id: +id,
        },
        [
            { model: 'users', attributes: ['id', 'nickname'], as: 'user' },
            {
                model: 'knowledgeBases',
                attributes: ['id', 'title', 'collectionName'],
                as: 'knowledgeBase',
            },
            {
                model: 'questions',
                as: 'questions',
            },
        ]
    )
    if (!res.success) return
    caseData.value = res.data.rows[0]
}

// 分享
const handleShare = () => {
    const url = window.location.href
    navigator.clipboard.writeText(url)
    ElMessage.success('分享链接已复制到剪贴板')
}

// 窗口尺寸变化
const handleResize = throttle(() => {
    if (!leaferApp || !containerRef.value) return
    const dom = containerRef.value
    const domWidth = parseInt(getComputedStyle(dom).width)

    leaferApp.resize({
        width: domWidth - 400,
        height: 800,
    })
    leaferApp.tree.zoom('fit')
}, 1000)

onMounted(() => {
    const app = new App({
        view: 'leafer-view',
        tree: {
            type: 'design',
        },
        move: {
            // disabled: true,
        },
    })

    leaferApp = app

    // app.on(ResizeEvent.RESIZE, () => {
    //     app.tree.zoom('fit')
    // })

    window.addEventListener('resize', handleResize)

    load(`/src/teaching-cases/${route.params.name}/index.ts`)
    getData()
    // const dotMatrix = new DotMatrix(app)
    // // 启用点阵显示
    // dotMatrix.enableDotMatrix(true)

    setTimeout(() => {
        app.tree.zoom('fit')
    }, 1000)
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    if (imported.value?.emitter) {
        imported.value.emitter.clear()
    }
})
</script>

<style scoped></style>
